package pers.sloera.leetcode.editor.cn;

import java.util.Stack;

/**
 * 行星碰撞
 *
 * @author sloera
 * @date 2022-07-13 20:57:16
 */
class AsteroidCollision {
    public static void main(String[] args) {
        Solution solution = new AsteroidCollision().new Solution();
        // int[] ints = solution.asteroidCollision(new int[]{5, 10, -5});
        // int[] ints = solution.asteroidCollision(new int[]{8,-8});
        int[] ints = solution.asteroidCollision(new int[]{10, 2, -5});
        System.out.println();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] asteroidCollision(int[] asteroids) {
            Stack<Integer> stack = new Stack<>();
            int i = 0;
            while (i < asteroids.length) {
                if (stack.isEmpty()) {
                    stack.add(asteroids[i++]);
                    continue;
                }
                int left = stack.pop();
                int right = asteroids[i];
                boolean leftPositive = left > 0;
                boolean rightPositive = right > 0;
                // 1. 两个符号相同，接着处理下一个
                // 左边的需要删除，再取一个左边的进行比较，直到为空
                // 右边的需要删除，取下一个数
                // 左边为负，直接都存进去
                // 只有左边为正，右边为负才需要碰撞
                if (leftPositive && !rightPositive) {
                    if (Math.abs(left) == Math.abs(right)) {
                        i++;
                        // 找下一个，左右都删除
                    } else if (Math.abs(left) > Math.abs(right)) {
                        stack.add(left);
                        i++;
                        // 左边的放回去，右边加1，进行处理
                    }
                    // 左边小，继续比较右边的这个数
                } else {
                    stack.add(left);
                    stack.add(right);
                    i++;
                }
            }
            return stack.stream().mapToInt(x -> x).toArray();
        }

    }
    //leetcode submit region end(Prohibit modification and deletion)

}
